package accounts

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"minititok/Entities"
	"minititok/Services"
	"net/http"
	"os"
	"path/filepath"
)

func getAvatar(c *gin.Context) {
	filename := c.Param("filename")
	filepath := filepath.Join("./staticSrc/staticAvatar/", filename)
	if c.Request.Method != http.MethodGet {
		c.String(http.StatusNotFound, "<h1>Page not found</h1>")
		_ = c.Error(fmt.Errorf("错误的请求方式:" + c.Request.Method))
		return
	}
	if _, err := os.Stat(filepath); os.IsNotExist(err) {
		_ = c.Error(fmt.Errorf("文件获取失败:"+filepath+",%w", err))
		c.JSON(http.StatusNotFound, gin.H{"customMessage": "头像可能因违规被删除"})
		return
	}
	c.File(filepath)
}

func upLoadAvatar(c *gin.Context) {
	AvatarFile, err := c.FormFile("avatar")
	if err != nil {
		_ = c.Error(fmt.Errorf("上传失败:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessages": "文件错误"})
		return
	}
	AvatarPath := filepath.Join("./staticSrc/staticAvatar/", AvatarFile.Filename)
	if Ferr := c.SaveUploadedFile(AvatarFile, AvatarPath); Ferr != nil {
		_ = c.Error(fmt.Errorf("文件保存失败:" + Ferr.Error() + ",路径:" + AvatarPath))
		c.JSON(http.StatusBadRequest, gin.H{"customMessages": "文件保存失败"})
		return
	}

	currUser, _ := c.Get("user")

	user, ok := currUser.(*Entities.User)
	if !ok {
		_ = c.Error(fmt.Errorf("上下文验证失败,token错误"))
		c.JSON(http.StatusInternalServerError, gin.H{"customMessages": "身份验证失败"})
		return
	}

	AvatarUrl := "http://localHost:8000/getAvatar/" + AvatarFile.Filename

	user.Avatar = AvatarUrl
	errA := Services.UpdateAvatar(user)
	if errA != nil {
		_ = c.Error(fmt.Errorf("数据库错误,AvatarUrl更新失败:" + errA.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessages": "未知错误"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"customMessages": "success"})
}
